/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DiscoverServices.java
 *
 * Created on Feb 26, 2010, 8:11:02 PM
 */
package jobserviceclient;

import java.net.PasswordAuthentication;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.xml.registry.BulkResponse;
import javax.xml.registry.BusinessLifeCycleManager;
import javax.xml.registry.BusinessQueryManager;
import javax.xml.registry.Connection;
import javax.xml.registry.ConnectionFactory;
import javax.xml.registry.FindQualifier;
import javax.xml.registry.JAXRException;
import javax.xml.registry.LifeCycleManager;
import javax.xml.registry.RegistryService;
import javax.xml.registry.infomodel.Classification;
import javax.xml.registry.infomodel.ClassificationScheme;
import javax.xml.registry.infomodel.InternationalString;
import javax.xml.registry.infomodel.Organization;
import javax.xml.registry.infomodel.Service;

/**
 *
 * @author wangyu
 */
public class DiscoverServices extends javax.swing.JFrame {

    /** Creates new form DiscoverServices */
    public DiscoverServices() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        rbName = new javax.swing.JRadioButton();
        rbClassification = new javax.swing.JRadioButton();
        btnSearch = new javax.swing.JButton();
        btnRun = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbSearch = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Organization:");

        buttonGroup1.add(rbName);
        rbName.setSelected(true);
        rbName.setText("By Name");

        buttonGroup1.add(rbClassification);
        rbClassification.setText("By Classification");

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        btnRun.setText("Run");
        btnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRunActionPerformed(evt);
            }
        });

        tbSearch.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Classification", "Organization", "Service"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbSearch);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rbClassification)
                    .addComponent(rbName))
                .addGap(18, 18, 18)
                .addComponent(btnSearch)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(408, Short.MAX_VALUE)
                .addComponent(btnRun)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(15, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(btnSearch))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(rbName)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rbClassification)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnRun))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        ArrayList<String[]> results = new ArrayList<String[]>();
        try {
            // ------------------- Set Connection properties -------------------
            Properties connProps = new Properties();
            connProps.setProperty("javax.xml.registry.queryManagerURL", "http://localhost:8080/RegistryServer/");
            connProps.setProperty("javax.xml.registry.lifeCycleManagerURL", "http://localhost:8080/RegistryServer/");
            connProps.setProperty("javax.xml.registry.factoryClass", "com.sun.xml.registry.uddi.ConnectionFactoryImpl");
            // ------------------- Set Connection Factory -------------------
            ConnectionFactory factory = ConnectionFactory.newInstance();
            factory.setProperties(connProps);
            Connection conn = factory.createConnection();
            // ---------------- Getting Registry service Object ---------------
            RegistryService rs = conn.getRegistryService();
            BusinessQueryManager bqm = rs.getBusinessQueryManager();
            BusinessLifeCycleManager blcm = rs.getBusinessLifeCycleManager();
            String username = "testuser";
            String password = "testuser";
            // Get authorization from the registry
            PasswordAuthentication passwdAuth =
                    new PasswordAuthentication(username, password.toCharArray());
            HashSet<PasswordAuthentication> creds =
                    new HashSet<PasswordAuthentication>();
            creds.add(passwdAuth);
            conn.setCredentials(creds);

            if (rbName.isSelected()) {
                // Define find qualifiers and name patterns
                Collection<String> findQualifiers = new ArrayList<String>();
                findQualifiers.add(FindQualifier.SORT_BY_NAME_DESC);
                Collection<String> namePatterns = new ArrayList<String>();
                // qString refers to the organization name we are looking for
                namePatterns.add(txtName.getText());
                // Find orgs with names that matches qString
                BulkResponse response = bqm.findOrganizations(findQualifiers, namePatterns, null, null, null, null);

                //Iterate over discovered organizations and collect their service binding
                Collection orgs = response.getCollection();
                Iterator orgIter = orgs.iterator();
                while (orgIter.hasNext()) {
                    Organization org = (Organization) orgIter.next();
                    Collection services = org.getServices();
                    Iterator svcIter = services.iterator();
                    String organization = org.getName().getValue();
                    while (svcIter.hasNext()) {
                        Service svc = (Service) svcIter.next();
                        results.add(new String[] {((Classification)org.getClassifications().iterator().next()).getName().getValue(),
                        organization, svc.getName().getValue()});
                    }
                }
            } else {
                // NAICS classification(taxonomy) uuid
                String uuid_naics = "uuid:C0B9FE13-179F-413D-8A5B-5004DB8E5BB2";
                ClassificationScheme cScheme = (ClassificationScheme) bqm.getRegistryObject(uuid_naics, LifeCycleManager.CLASSIFICATION_SCHEME);
                /** we are looking for Simple Data Processing Services with
                514211 identifier in NAICS taxonomy
                 */
                InternationalString sn = blcm.createInternationalString(txtName.getText());
                String sv = "";
                if(txtName.getText().contains("Businese")){
                    sv = "514211";
                } else if(txtName.getText().contains("Education")) {
                    sv = "514212";
                } else {
                    return;
                }
                
                Classification classification = blcm.createClassification(cScheme, sn, sv);
                Collection<Classification> classifications = new ArrayList<Classification>();
                classifications.add(classification);


                // Submit query to Registry
                BulkResponse response1 = bqm.findOrganizations(null, null, classifications, null, null, null);
                Collection orgs1 = response1.getCollection();
                // Display information about the organizations found
                Iterator orgIter1 = orgs1.iterator();
                while (orgIter1.hasNext()) {
                    Organization org = (Organization) orgIter1.next();
                    Collection services = org.getServices();
                    Iterator svcIter = services.iterator();
                    String organization = org.getName().getValue();
                    while (svcIter.hasNext()) {
                        Service svc = (Service) svcIter.next();
                        results.add(new String[] {((Classification)org.getClassifications().iterator().next()).getName().getValue(),
                        organization, svc.getName().getValue()});
                    }
                }
            }
        } catch (JAXRException ex) {
            Logger.getLogger(DiscoverServices.class.getName()).log(Level.SEVERE, null, ex);
        }

        String[][] data = new String[results.size()][3];
        for(int i = 0; i < results.size(); i++) {
            for(int j = 0; j < 3; j++) {
                data[i][j] = results.get(i)[j];
            }
        }
        setModel(data, new String[] {"Classification", "Organization", "Service"});
    }//GEN-LAST:event_btnSearchActionPerformed

    private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRunActionPerformed
        if(tbSearch.getSelectedRow() < 0) {
            JOptionPane.showMessageDialog(this, "Please select a service");
        }
        String service = tbSearch.getModel().getValueAt(tbSearch.getSelectedRow(), 2).toString();
        if(service.equals("GetApplicantProfile")) {
            new MainFrame().setVisible(true);
        } else if(service.equals("GetCompanyInfo") || service.equals("GetTranscripts")
                || service.equals("GetEmploymentRecord")) {
            new CheckInfo(this, true).setVisible(true);
        } else if( service.equals("SearchJob")) {
            new SearchJob(this, true).setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "Not supported service!");
        }
    }//GEN-LAST:event_btnRunActionPerformed

    private void setModel(Object[][] objects, String[] titles) {
         tbSearch.setModel(new javax.swing.table.DefaultTableModel(objects, titles)
         {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false
            };

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DiscoverServices().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnRun;
    private javax.swing.JButton btnSearch;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbClassification;
    private javax.swing.JRadioButton rbName;
    private javax.swing.JTable tbSearch;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
}
